require "IntensifyPanel"
require "SettingPanel"
require "levelCfg"
require "levelData"
require "LoginAwardPanel"
require "UnlockPanel"
require "BuyCoinPanel"
require "LotteryPanel"
require "AchievePanel"

local image_bt_levelactive = "level/gkx2.png"
local s_strdef = require "res/commonStrDef"
local s_levelDesc = s_strdef.level
local s_uiinfo_desc = UIInfo:create()
local s_uiinfo_levelbtn_idx = UIInfo:create()
local s_uiinfo_levelbtn_star = UIInfo:create()
local s_uiinfo_flyend = UIInfo:create()
local s_img_stars = {
    [0] = "level/xk.png",
    [1] = "level/x1.png",
    [2] = "level/x2.png",
    [3] = "level/x3.png",
}

local s_uiinfo_lock = UIInfo:create()

local s_lockcnt_max = 50
-- local img_yellowlock = "level/lock.png"
-- local s_tag_yellowlock = 7000

local s_img_lock_active = "level/lock-c.png"
local s_img_lock_unlocked = "level/lock-k.png"


local scheduler = cc.Director:getInstance():getScheduler()

LevelScene = class("LevelScene", baseScene)

function LevelScene.create()
     local scene = LevelScene.new()
    scene:init()

    local popAward = scene:checkLoginObjects()

    if not popAward then
        scene:checkPopLiBao()
    end

	return scene
end

function LevelScene:destroy()
    --may fix bug
    scheduler:unscheduleScriptEntry(self.schedulerScrollPercentEntry)
end

function LevelScene:checkPopLiBao()
    if gameData.changeSceneTimes.levelScene == 1 then
        if not userData.bought_xinshoulibao and gameData.SwichByServer.popXinShouLiBao then
            WarningPanel.create(self,"Pay_level_Libao_Xinshou")
            
        else
            if gameData.SwichByServer.popChangWanLiBao and userData.fulllives ~= pp.lives_fullcnt_high then
                WarningPanel.create(self,"Pay_ChangwanGift")
            end
        end
    end
end

function LevelScene:init()
    gameData.changeSceneTimes.levelScene = gameData.changeSceneTimes.levelScene + 1
    --load res
    resMgr.loadRes_level()

    gameUtil.playMusic(music.level, true)

    self.view = cc.Scene:create()
    
    self.widget = ccs.GUIReader:getInstance():widgetFromJsonFile("levelScene.json")
    self.view:addChild(self.widget)  
    self.ui_scroll = self.widget:getChildByName("_scroll")
    self.ui_scroll:setBounceEnabled(false)
    local innerSize = self.ui_scroll:getInnerContainerSize()


    self.ui_btCtn = self.ui_scroll:getChildByName("_bts")
    self.ui_fnt_coin = nil
    self.ui_fnt_livescnt = nil
    self.locks = {}

    -- self.settingPanel = nil
    -- self.intensifyPanel = nil
    
    self.schedulerScrollPercentEntry = nil
    --lkj hard code:这里_bts是在_scroll上的，且它的y = 8000，而scroll height = 6600,要计算相对位置
    local function scrollSetInnerPercent()
        --self.ui_scroll:jumpToBottom() 
        --self.ui_scroll:jumpToPercentVertical(90, 0.5, true)
        
        local curlevelbt = self.ui_btCtn:getChildByTag(#userData.passedlevelinfo)
        local curY = curlevelbt:getPositionY()      
        curY = -(curY + (8000-6600))
        
        local halfFrameHeight = pp.visibleSize.height*0.5
        local percent
        if curY < halfFrameHeight then
            percent = 0
        elseif curY > innerSize.height - halfFrameHeight then
            percent = 100
        else
            percent = (curY - halfFrameHeight) / (innerSize.height - pp.visibleSize.height)*100        
        end
        --local percent = (curY - halfFrameHeight) / 6400 * 100

        self.ui_scroll:jumpToPercentVertical(percent)
        
        scheduler:unscheduleScriptEntry(self.schedulerScrollPercentEntry)
    end  
    self.schedulerScrollPercentEntry = scheduler:scheduleScriptFunc(scrollSetInnerPercent, 0, false)


    
    local bt1 = self.ui_btCtn:getChildByTag(1)

    local idx_ = bt1:getChildByName("_idx")
    local star_ = bt1:getChildByName("_star")
    s_uiinfo_levelbtn_idx:readInfoFromNode(idx_)
    idx_:removeFromParent(true)
    s_uiinfo_levelbtn_star:readInfoFromNode(star_)
    star_:removeFromParent(true)


    --locks
    for i = 1, s_lockcnt_max do 
        local lockname = string.format("s_%d",i)
        local lock_ = self.ui_btCtn:getChildByName(lockname)
        if lock_ then
            self.locks[#self.locks+1] = lock_
            --record ui info
            -- if i == 1 then
            --     local yellowlock = lock_:getChildByName("_lock")
            --     s_uiinfo_lock:readInfoFromNode(yellowlock)
            --     yellowlock:removeFromParent(true)
            -- end
            
        else
            break
        end
    end

 

    local passedlevelcnt = #userData.passedlevelinfo
 ---[[  enable level lock

    --如果通关到了锁关，判断是否解锁，解了显示后一关，否则不显示
    local levelcntBehindLock = passedlevelcnt%levelCfg.lockInterval
    
    local showlevelcnt
    if passedlevelcnt > levelCfg.lockInterval and levelcntBehindLock == 1 and not userData.lockUnlocked then
        showlevelcnt = #userData.passedlevelinfo - 1
    else
        showlevelcnt = #userData.passedlevelinfo
    end


    for i = 1,showlevelcnt do
        local function btLevelCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)

            elseif eventType == ccui.TouchEventType.ended then
                local tag = sender:getTag()
                gameData.level = tag
                self:popLevelPanel()
             end
        end
        local bt = self.ui_btCtn:getChildByTag(i)
        if bt then
            --idx
            local levelstring = string.format("%d", i)
            local fnt = cc.LabelBMFont:create(levelstring,  pp.fnt_number_white)
            s_uiinfo_levelbtn_idx:setInfoToNode(fnt)
            bt:loadTextureNormal(image_bt_levelactive, ccui.TextureResType.localType)
            bt:addChild(fnt)
            bt:addTouchEventListener(btLevelCallback)

            fnt:setScale(0.5)

            --star
            local imgstars=  ccui.ImageView:create(s_img_stars[userData.passedlevelinfo[i].stars], ccui.TextureResType.localType)
            s_uiinfo_levelbtn_star:setInfoToNode(imgstars)
            bt:addChild(imgstars)
        end
    end
    for i = showlevelcnt+1, 500 do
        local bt = self.ui_btCtn:getChildByTag(i)
        if not bt then
            break
        end
        bt:setEnabled(false)
    end
    --]]

    --[[ disable level lock
    for k = 1,200 do

        local bt = self.ui_btCtn:getChildByTag(k)
        if bt then
            local levelstring = string.format("%d", k)
            local fnt = cc.LabelBMFont:create(levelstring,  pp.fnt_number_white)

            bt:loadTextureNormal(image_bt_levelactive, ccui.TextureResType.localType)
            bt:addChild(fnt)
            bt:addTouchEventListener(btLevelCallback)
            
            fnt:setPosition(btcx,btcy)   
            fnt:setScale(0.5)
        end
    end
    --]]


    --enable lock
    
    for i = 1, #self.locks do
        local levelBeforeLock = levelCfg.lockInterval * i
        local lock_ = self.locks[i]

        if levelBeforeLock > passedlevelcnt-1 then
            lock_:setEnabled(false)           

        elseif levelBeforeLock == passedlevelcnt-1 and not userData.lockUnlocked then
--            lock_:setOpacity(0)
            lock_:setEnabled(true)

            local function toUnlock(sender, eventType)
                if eventType == ccui.TouchEventType.began then
                    AudioEngine.playEffect(sound.btn1)

                elseif eventType == ccui.TouchEventType.ended then
                    UnlockPanel.create(self)
                end
            end
            lock_:addTouchEventListener(toUnlock)
            self.activeLock = lock_

            -- UIInfo.inst:readInfoFromNode(lock_)
            -- local parent = lock_:getParent()

            -- local lockani = uiAnimation.create("lock", true)
            -- UIInfo.inst:setInfoToNode(lockani)
            -- parent:addChild(lockani)

            -- --yellow icon            
            -- self.yellowLock =  ccui.ImageView:create(img_yellowlock, ccui.TextureResType.localType)
            -- s_uiinfo_lock:setInfoToNode(self.yellowLock)
            -- lockani:addChild(self.yellowLock)

            lock_:loadTextureNormal(s_img_lock_active, ccui.TextureResType.localType)
            
        elseif levelBeforeLock < passedlevelcnt-1 or
            levelBeforeLock == passedlevelcnt-1 and userData.lockUnlocked == true
            then
--            lock_:setOpacity(0)
            lock_:setEnabled(false)

            -- UIInfo.inst:readInfoFromNode(lock_)
            -- local parent = lock_:getParent()

            -- local lockani = uiAnimation.create("lock", true)
            -- UIInfo.inst:setInfoToNode(lockani)
            -- parent:addChild(lockani)

            lock_:loadTextureNormal(s_img_lock_unlocked, ccui.TextureResType.localType)
        end

    end

    --xuanzhong eft

--     self.focusEft = ccui.ImageView:create("common/xuanzhong.png", ccui.TextureResType.localType)
--     self.ui_btCtn:addChild(self.focusEft, 50)

--     local function resetEft()
--         self.focusEft:setScale(0.6)
--         self.focusEft:setColor(cc.c3b(255,255,255))
--         self.focusEft:setOpacity(255)
--     end

--     local scale_ease_in = cc.EaseInOut:create(cc.ScaleTo:create(0.5, 1.3), 1.1)
--     local tint_ = cc.TintTo:create(0.5, 255, 255, 255)
--     --local scale_ease_in_back = cc.EaseInOut:create(cc.ScaleTo:create(0.4, 0.9), 1.8)
--     --local fadeOut_ = cc.FadeOut:create(0.4)
--     local seq = cc.Sequence:create(
--         cc.Spawn:create(scale_ease_in,
--                         tint_,
--                         cc.Sequence:create(cc.DelayTime:create(0.4), cc.FadeOut:create(0.1))
--                         ),
--         cc.CallFunc:create(resetEft))
-- --        scale_ease_in,scale_ease_in_back, )
--     self.focusEft:runAction(cc.RepeatForever:create(seq))

    --bug 2014/12/30  replace it into onEnter event handle
    -- ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/xuanzhong/xuanzhong.ExportJson")
    -- ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/xuanzhong/xuanzhong.ExportJson")
    -- self.focusEft = ccs.Armature:create("xuanzhong")
    -- self.focusEft:getAnimation():playWithIndex(0)
    -- self.ui_btCtn:addChild(self.focusEft,50)



    --mask
    do --mask
        self.base_mask = self.widget:getChildByName("_mask")
        self.base_mask:setVisible(false)
    end

    --fly heart
    do
        self.fly_heart = self.widget:getChildByName("_fly_heart")
        self.fly_heart:setOpacity(0)
        local fly_end = self.widget:getChildByName("_holder_flyend")
        s_uiinfo_flyend:readInfoFromNode(fly_end)
        fly_end:removeFromParent(true)
    end
    
    --level info
    do
        self.ui_levelinfo = self.widget:getChildByName("_level_info")
        self.ui_levelinfo:setVisible(false)

        self.fnt_level = uiUtil.createBMFontByHolder(self.ui_levelinfo, "_fnt_level", pp.fnt_level)
        self.fnt_level:setScale(1.5)

        --stars
        do
            self.star1 = self.ui_levelinfo:getChildByName("_star1_0")
            self.star2 = self.ui_levelinfo:getChildByName("_star2_0")
            self.star3 = self.ui_levelinfo:getChildByName("_star3_0")
            self.star1:setVisible(false)
            self.star2:setVisible(false)
            self.star3:setVisible(false)

        end



        --desc
        local leveldesc = self.ui_levelinfo:getChildByName("_desc")
        s_uiinfo_desc:readInfoFromNode(leveldesc)
        leveldesc:removeFromParent(true)
        

        local function btStartCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then                  
                if userData.lives > 0 then
                    self.btStart:setEnabled(false)
                    local level = gameData.level

                    --add daoju
                    if self.djSel1:isVisible() == true then
                        userData.weaponCnt_fenji = userData.weaponCnt_fenji + levelCfg.fenji_buy_cnt                        
                    end
                    if self.djSel2:isVisible() == true then
                        userData.weaponCnt_yuheng = userData.weaponCnt_yuheng + levelCfg.yuheng_buy_cnt                        
                    end
                    userData.coin = userData.coin - self.willCostPrize


                    userData:lives_castOne()
                    gameUtil.flushUserRecord()
                    self.ui_fnt_livescnt:setString(string.format("%d",userData.lives))

                    --heart fly
                    local bezier = {
                        cc.p(-pp.visibleSize.width*0.1,-pp.visibleSize.height*0.2),
                        cc.p(-pp.visibleSize.width*0.4,-pp.visibleSize.height*1.0),
                        cc.pSub(s_uiinfo_flyend.position,cc.p(self.fly_heart:getPosition()))
                    }
                    local moveBzr = cc.BezierBy:create(1.0, bezier)
                    self.fly_heart:runAction(cc.Sequence:create(cc.DelayTime:create(0.2), moveBzr))
                    self.fly_heart:runAction(cc.FadeIn:create(0.3))

                     --playSound
                    local function delay_playSound()
                        AudioEngine.playEffect(sound.costLife)
                    end
                    performWithDelay(self.widget, delay_playSound,1.0)

                    --start changescene
                    local function delay_start()
                        gameUtil.changeScene("game")
                    end
                    performWithDelay(self.widget, delay_start,1.27)

                    gameUtil.sendGameStat(et.Level_Start, gameData.level)
                else
                    if userData.fulllives ~= pp.lives_fullcnt_high then
                        WarningPanel.create(self,"Pay_ChangwanGift")
                        self.bNeedPopBuyLifePanel = true
                    else
                        WarningPanel.create(self, "Pay_buyLife")
                    end        
                end                            
            end
        end
        self.btStart = self.ui_levelinfo:getChildByName("_start")
        self.btStart:addTouchEventListener(btStartCallback)
--        uiEffect.jelly(self.btStart)
        
        local function btCloseCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn2)
            elseif eventType == ccui.TouchEventType.ended then    
                -- uiEffect.maskOut(self.base_mask)

                self:base_onCloseWin(self.ui_levelinfo)

                --lkj hard code:
                ----------------------------------
                -- for k,v in ipairs(self.base_popWinStack)do
                --     if v == self.ui_levelinfo then
                --         table.remove(self.base_popWinStack, k)
                --     end
                -- end
                -- if #self.base_popWinStack == 0 then
                --     uiEffect.maskOut(self.base_mask)
                -- else
                --     local topwin = self.base_popWinStack[#self.base_popWinStack]
                --     local zorder = topwin.view:getLocalZOrder()
                --     self.base_mask:setLocalZOrder(zorder - 1)
                -- end

                ----------------------------------

                uiEffect.bounceOut(self.ui_levelinfo)

                --hard code
                local function setUnvisibleLevelInfoPanel()
                    self.ui_levelinfo:setVisible(false)
                end
                self.view:runAction(cc.Sequence:create(
                        cc.DelayTime:create(0.4),
                        cc.CallFunc:create(setUnvisibleLevelInfoPanel)
                    )) 
                self:refreshCoin(userData.coin)
                self.willCostPrize = 0
            end
        end
        local btClose = self.ui_levelinfo:getChildByName("_close")
        btClose:addTouchEventListener(btCloseCallback)

        --bug daoju

        local fnt_djCnt1 = uiUtil.createBMFontByHolder(self.ui_levelinfo, "_daoju1_num", pp.fnt_number_white)
        fnt_djCnt1:setString(string.format("×%d", levelCfg.fenji_buy_cnt))
        fnt_djCnt1:setScale(0.6)

        local fnt_djCnt2 = uiUtil.createBMFontByHolder(self.ui_levelinfo, "_daoju2_num", pp.fnt_number_white)
        fnt_djCnt2:setString(string.format("×%d", levelCfg.yuheng_buy_cnt))
        fnt_djCnt2:setScale(0.6)

        local fnt_djPrize1 = uiUtil.createBMFontByHolder(self.ui_levelinfo, "_coin_cnt1", pp.fnt_number_yellow)
        fnt_djPrize1:setString(string.format("%d", levelCfg.fenji_buy_prize))
        fnt_djPrize1:setScale(0.65)

        local fnt_djPrize2 = uiUtil.createBMFontByHolder(self.ui_levelinfo, "_coin_cnt2", pp.fnt_number_yellow)
        fnt_djPrize2:setString(string.format("%d", levelCfg.yuheng_buy_prize))
        fnt_djPrize2:setScale(0.65)

        
        self.djSel1 = self.ui_levelinfo:getChildByName("_sel1")
        self.djSel2 = self.ui_levelinfo:getChildByName("_sel2")


        --1
        self.willCostPrize = 0
        local function btDj1Callback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then    
                if self.djSel1:isVisible() == true then
                    self.djSel1:setVisible(false)
                    self.willCostPrize = self.willCostPrize - levelCfg.fenji_buy_prize
                else                                        
                    if userData.coin >= self.willCostPrize + levelCfg.fenji_buy_prize then
                        self.willCostPrize = self.willCostPrize + levelCfg.fenji_buy_prize
                        self.djSel1:setVisible(true)

                        --lkj test:
                        --uiPopNotify:popString(self.widget, "大幅提升炸弹的出现几")
                    else
                        uiPopNotify:popString(self.widget, "金币不足")
                        if DEF_CHN_XNY then
                            pchCenter:order(pchCfg.item.JinBiLiBao)
                        else
                            WarningPanel.create(self, "Pay_level_Libao_Jinbi")
                        end
                    end
                    
                end
                self:refreshCoin(userData.coin - self.willCostPrize)
            end
        end
        local btDaoju1 = self.ui_levelinfo:getChildByName("_bt_daoju_bg1")
        btDaoju1:addTouchEventListener(btDj1Callback)
        uiEffect.jelly(btDaoju1)

        --2
        local function btDj2Callback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then   
                if self.djSel2:isVisible() == true then
                    self.djSel2:setVisible(false)
                    self.willCostPrize = self.willCostPrize - levelCfg.yuheng_buy_prize
                else
                    if userData.coin >= self.willCostPrize + levelCfg.yuheng_buy_prize then
                        self.willCostPrize = self.willCostPrize + levelCfg.yuheng_buy_prize
                        self.djSel2:setVisible(true)  
                    else
                        uiPopNotify:popString(self.widget, "金币不足")
                        if DEF_CHN_XNY then
                            pchCenter:order(pchCfg.item.JinBiLiBao)
                        else
                            WarningPanel.create(self, "Pay_level_Libao_Jinbi")
                        end  
                    end        
                     
                end
                self:refreshCoin(userData.coin - self.willCostPrize)
            end
        end
        local btDaoju2 = self.ui_levelinfo:getChildByName("_bt_daoju_bg2")
        btDaoju2:addTouchEventListener(btDj2Callback)
        uiEffect.jelly(btDaoju2)


        -----------------------------------------------------
        --没有过前两关，道具加锁
        if #userData.passedlevelinfo <= levelCfg.lockDaojuLevel then
            fnt_djCnt1:setVisible(false)
            fnt_djCnt2:setVisible(false)
            fnt_djPrize1:setVisible(false)
            fnt_djPrize2:setVisible(false)
            btDaoju1:setVisible(false)
            btDaoju2:setVisible(false)
            self.djSel1:setVisible(false)
            self.djSel2:setVisible(false)
            local daoju1 = self.ui_levelinfo:getChildByName("_daoju1")
            daoju1:setVisible(false)
            local daoju2 = self.ui_levelinfo:getChildByName("_daoju2")
            daoju2:setVisible(false)
            local coin1 = self.ui_levelinfo:getChildByName("coin1")
            coin1:setVisible(false)
            local coin2 = self.ui_levelinfo:getChildByName("coin2")
            coin2:setVisible(false)
        else
            local locker1 = self.ui_levelinfo:getChildByName("_daoju_disable1")
            locker1:setVisible(false)
            local locker2 = self.ui_levelinfo:getChildByName("_daoju_disable2")
            locker2:setVisible(false)
        end

    end

    --top bts
    do --coin
        local btCoin = self.widget:getChildByName("_bt_coin")

        local function btCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then    
                BuyCoinPanel.create(self)
             
            end
        end
        btCoin:addTouchEventListener(btCallback)

        local fntCoin = btCoin:getChildByName("_fnt_coin")
        UIInfo.inst:readInfoFromNode(fntCoin)
        fntCoin:removeFromParent(true)

        local str = string.format("%d", userData.coin)
        self.ui_fnt_coin = cc.LabelBMFont:create(str,  pp.fnt_number_yellow)
        UIInfo.inst:setInfoToNode(self.ui_fnt_coin)
        btCoin:addChild(self.ui_fnt_coin)
        self.ui_fnt_coin:setScale(0.6)
    end
    
    do --lives
        local btlives = self.widget:getChildByName("_bt_lives")
        
        local function btCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then 

                if userData.fulllives ~= pp.lives_fullcnt_high then
                    WarningPanel.create(self, "Pay_ChangwanGift")
                    self.bNeedPopBuyLifePanel = true
                else
                    if userData.lives ~= userData.fulllives then
                        WarningPanel.create(self, "Pay_buyLife")
                    end
                end               
              
            end
        end
        btlives:addTouchEventListener(btCallback)


        local fntlives = btlives:getChildByName("_fnt_lives")
        UIInfo.inst:readInfoFromNode(fntlives)
        fntlives:removeFromParent(true)

        local str = string.format("%d", userData.lives)
        self.ui_fnt_livescnt = cc.LabelBMFont:create(str,  pp.fnt_number_yellow)
        UIInfo.inst:setInfoToNode(self.ui_fnt_livescnt)
        btlives:addChild(self.ui_fnt_livescnt)
        self.ui_fnt_livescnt:setScale(0.6)


        local fntlefttime = btlives:getChildByName("_fnt_lefttime")
        UIInfo.inst:readInfoFromNode(fntlefttime)
        fntlefttime:removeFromParent(true)

        self.ui_fnt_lefttime = cc.LabelBMFont:create("",  pp.fnt_number_white)
        UIInfo.inst:setInfoToNode(self.ui_fnt_lefttime)
        btlives:addChild(self.ui_fnt_lefttime)
        self.ui_fnt_lefttime:setScale(0.5)
    end

    do  --libao
        self.bt_libao = self.widget:getChildByName("_bt_libao")
        if userData.fulllives ~= pp.lives_fullcnt_high then
            local function btCallback(sender, eventType)
                if eventType == ccui.TouchEventType.began then
                    AudioEngine.playEffect(sound.btn1)
                elseif eventType == ccui.TouchEventType.ended then    
                    WarningPanel.create(self, "Pay_ChangwanGift")

                end
            end
            self.bt_libao:addTouchEventListener(btCallback)
        else
            self.bt_libao:removeFromParent(true)
        end
        -- uiEffect.blink(self.bt_libao)
        self.bt_libao:setScale(0.8)
        uiEffect.jelly(self.bt_libao)
        uiCreator.createAni_Zhuan(self.bt_libao, "ani/cwlbzhuan.png", 1.1)
    end

    --lkj version: del 2015/1/29
    --lkj version: add 2015/2/11
    do  --xinshou libao
        self.bt_xinshou_libao = self.widget:getChildByName("_bt_xinshou_libao")
        if gameData.SwichByServer.popXinShouLiBao then
            if userData.bought_xinshoulibao then
                self.bt_xinshou_libao:removeFromParent(true)
            else
                local function btCallback(sender, eventType)
                    if eventType == ccui.TouchEventType.began then
                        AudioEngine.playEffect(sound.btn1)
                    elseif eventType == ccui.TouchEventType.ended then    
                        WarningPanel.create(self, "Pay_level_Libao_Xinshou")
                    end
                end
                self.bt_xinshou_libao:addTouchEventListener(btCallback)
                self.bt_xinshou_libao:setScale(0.8)
                uiEffect.jelly(self.bt_xinshou_libao)
                uiCreator.createAni_Zhuan(self.bt_xinshou_libao, "ani/cwlbzhuan.png", 1.1)
            end
        else
            self.bt_xinshou_libao:removeFromParent(true)
        end
        
    end

    do  --lottery
        local function btCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then    
                assert(not self.lotteryPanel, "lotteryPanel should == nil")
                self.lotteryPanel = LotteryPanel.create(self)
            end
        end
        self.bt_lottery = self.widget:getChildByName("_bt_lottery")
        self.bt_lottery:addTouchEventListener(btCallback)
        
        self.bt_lottery:setVisible(false)

        self.ui_fnt_lottery_lefttime = uiUtil.createBMFontByHolder(self.bt_lottery, "_fnt_lefttime", pp.fnt_number_white)
        self.ui_fnt_lottery_lefttime:setScale(0.5)
    end

    do  --qianghua
        local function btCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then    
                -- uiEffect.maskIn(self.base_mask)
                IntensifyPanel.create(self)
            end
        end
        local bt = self.widget:getChildByName("_bt_qianghua")
        bt:addTouchEventListener(btCallback)
    end

    --lkj version: del 2015/1/29 
    -- do  --help
    --     local function btCallback(sender, eventType)
    --         if eventType == ccui.TouchEventType.began then
    --             AudioEngine.playEffect(sound.btn1)
    --         elseif eventType == ccui.TouchEventType.ended then    
    --             --uiEffect.maskIn(self.mask)          
    --             --uiEffect.bounceOut(self.ui_levelinfo)

    --             AchievePanel.create(self)

    --         end
    --     end
    --     local bt = self.widget:getChildByName("_bt_help")
    --     bt:addTouchEventListener(btCallback)
    --     --lkj hide:
    --     bt:setVisible(false)
    -- end

    do  --setting
        local function btCallback(sender, eventType)
            if eventType == ccui.TouchEventType.began then
                AudioEngine.playEffect(sound.btn1)
            elseif eventType == ccui.TouchEventType.ended then    
                uiEffect.maskIn(self.base_mask)
                SettingPanel.create(self)
              
            end
        end
        local bt = self.widget:getChildByName("_bt_setting")
        bt:addTouchEventListener(btCallback)
    end

    ----------------------------------------------------------
        --key
    local function onKeyReleased(keyCode, event)
        local view = event:getCurrentTarget()
        if keyCode == cc.KeyCode.KEY_ESCAPE then
            AudioEngine.playEffect(sound.btn1)
 
            local win = self:base_isWinOpened("WarningPanel") or self:base_isWinOpened("BuyCoinPanel")
            if win then
                win:close()
            else
                if cc.PLATFORM_OS_ANDROID == g_targetPlatform and DEF_CHN_CMjd then
                    local cs = require "purchase/channelSpecial"
                    cs.CMjd:exitGame()
                else
                    WarningPanel.create(self, "Common_leaveApp", pp.z_leaveApp)
                end

            end
           
        end
    end
    local listener = cc.EventListenerKeyboard:create()
    listener:registerScriptHandler(onKeyReleased, cc.Handler.EVENT_KEYBOARD_RELEASED )
    local eventDispatcher = self.view:getEventDispatcher()
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self.view)

    ---------------------------------------------------------

  
    local function update(delta)
       self:update(delta)
    end
    self.view:scheduleUpdateWithPriorityLua(update, 0)


    local function onNodeEvent(event)
        if "enter" == event then
            function addFocusEft()
                ccs.ArmatureDataManager:getInstance():removeArmatureFileInfo("ani/xuanzhong/xuanzhong.ExportJson")
                ccs.ArmatureDataManager:getInstance():addArmatureFileInfo("ani/xuanzhong/xuanzhong.ExportJson")
                self.focusEft = ccs.Armature:create("xuanzhong")
                self.focusEft:getAnimation():playWithIndex(0)
                self.ui_btCtn:addChild(self.focusEft,50)

                --focus effect
                if showlevelcnt == #userData.passedlevelinfo then
                    local bt = self.ui_btCtn:getChildByTag(showlevelcnt)
                    local x,y = bt:getPosition()
                    
                    --lkj todo now:
                    self.focusEft:setPosition(cc.p(x,y - 10))
                else
                    local level = showlevelcnt / levelCfg.lockInterval
                    local idx = math.floor(level)
                    local lock = self.locks[idx]
                    local x,y = lock:getPosition()
                    self.focusEft:setPosition(cc.p(x,y - 20))
                end
            end

            performWithDelay(self.view, addFocusEft, 0.8)
            
        end
    end
    self.view:registerScriptHandler(onNodeEvent)



    ----------------------------------------------------------
    if gameData.level_needPopLevelInfoPanel then
        self:popLevelPanel()
        gameData.level_needPopLevelInfoPanel = false
    end

    if gameData.level_needPopIntensifyPanel then
        IntensifyPanel.create(self)
        gameData.level_needPopIntensifyPanel = false
    end
end

function LevelScene:update(delta)

    local tm = os.date("*t")
    local sec = os.time(tm) 

    --reset
    if sec > userData.resetSec then
        userData.resetSec = userData:genResetSec()

        --do some reset of game thing
        userData:lottery_resetData()

        --refresh ui
        do 
            --lives
            self.ui_fnt_livescnt:setString(string.format("%d",userData.lives))

            --lottey ui
        end
    end

    --lives
    if userData.lives < userData.fulllives then
        local oldlives = userData.lives
        local timestr = userData:lives_restoreNeedTime()
        self.ui_fnt_lefttime:setString(timestr)
        if userData.lives ~= oldlives then
            self.ui_fnt_livescnt:setString(string.format("%d",userData.lives))
        end        
    end

    if uiIndicator.inst == nil and #userData.passedlevelinfo <= pp.levelMax then
        if self.activeLock then
            local x,y = self.activeLock:getPosition()
            local ind = uiIndicator:create(false)
            ind:setPosition(cc.p(x,y + 90))
            self.ui_btCtn:addChild(ind,200)

        elseif gameData.loginChecked then
            local ind = uiIndicator:create(false)
            local bt = self.ui_btCtn:getChildByTag(#userData.passedlevelinfo)
            local x,y = bt:getPosition()
            ind:setPosition(cc.p(x,y +70))
            self.ui_btCtn:addChild(ind,200)
        end
    end

    --lottery
    do
        local oldstr = self.ui_fnt_lottery_lefttime:getString()
        self.lotteryRestoreNeedTime = userData:lottery_restoreNeedTime()
        if self.lotteryRestoreNeedTime ~= oldstr then
            self.ui_fnt_lottery_lefttime:setString(self.lotteryRestoreNeedTime)

            if self.lotteryRestoreNeedTime == "" then
                if self.lotteryPanel then self.lotteryPanel:onTimeRestored() end
            end
        end
    end
    
end


function LevelScene:warningPanelCallback(type, btIdx, panel)
    if type == "Common_leaveApp" then
        if btIdx == 0 then
        elseif btIdx == 2 then
            panel:close()
        elseif btIdx == 1 then
            cc.Director:getInstance():endToLua()
        else
            
        end

    elseif type == "Pay_ChangwanGift" then
        if btIdx == 0 then
            if self.bNeedPopBuyLifePanel and userData.lives ~= userData.fulllives then
                --pop buy coin panel
                self.bNeedPopBuyLifePanel = nil
                WarningPanel.create(self, "Pay_buyLife")
            end
        elseif btIdx == 1 then
            self.bNeedPopBuyLifePanel = nil
            self.pchPanel = panel
            if pchCenter:order(pchCfg.item.ChangWanLiBao) == false then
                uiPopNotify:popString(self.widget, strDef.str_orderFail)
                panel:close()
                self.pchPanel = nil 
            end
        end 
           
    elseif type == "Pay_buyLife" then
        if btIdx == 0 then

        elseif btIdx == 1 then
            if userData.lives ~= userData.fulllives then
                self.pchPanel = panel
                if pchCenter:order(pchCfg.item.TiLiBuMan) == false then
                    uiPopNotify:popString(self.widget, strDef.str_orderFail)
                    panel:close()
                    self.pchPanel = nil
                end
            end
        end 
    
    elseif type == "Pay_level_Libao_Jinbi" then
        if btIdx == 0 then
        elseif btIdx == 1 then
            -- self.pchPanel = panel
            -- pchCfg.item.JinBiLiBao.processOk()
            
            self.pchPanel = panel
            if pchCenter:order(pchCfg.item.JinBiLiBao) == false then
                uiPopNotify:popString(self.widget, strDef.str_orderFail)
                panel:close()
                self.pchPanel = nil  
            end
        end

    elseif type == "Pay_level_Libao_Xinshou" then
        if btIdx == 0 then
        elseif btIdx == 1 then
            self.pchPanel = panel
            if pchCenter:order(pchCfg.item.XinShouLiBao) == false then
                uiPopNotify:popString(self.widget, strDef.str_orderFail)
                panel:close()
                self.pchPanel = nil    
            end
        end

    end

end

function LevelScene:activeLevel(i)
    local function btLevelCallback(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            AudioEngine.playEffect(sound.btn1)
        elseif eventType == ccui.TouchEventType.ended then
            local tag = sender:getTag()
            gameData.level = tag
            self:popLevelPanel()

            AudioEngine.playEffect(sound.btn1)
        end
    end
    local bt = self.ui_btCtn:getChildByTag(i)
        if bt then
            --idx
            local levelstring = string.format("%d", i)
            local fnt = cc.LabelBMFont:create(levelstring,  pp.fnt_number_white)
            s_uiinfo_levelbtn_idx:setInfoToNode(fnt)
            bt:loadTextureNormal(image_bt_levelactive, ccui.TextureResType.localType)
            bt:addChild(fnt)
            bt:addTouchEventListener(btLevelCallback)
            bt:setEnabled(true)

            fnt:setScale(0.5)

            --star
            local imgstars=  ccui.ImageView:create(s_img_stars[userData.passedlevelinfo[i].stars], ccui.TextureResType.localType)
            s_uiinfo_levelbtn_star:setInfoToNode(imgstars)
            bt:addChild(imgstars)
        end
end

function LevelScene:levelPanelInit()
    self.djSel1:setVisible(false)
    self.djSel2:setVisible(false)

    self.fnt_level:setString(string.format("关卡 %d", gameData.level))

    --stars
    self.star1:setVisible(false)
    self.star2:setVisible(false)
    self.star3:setVisible(false)
    local stars_ = userData.passedlevelinfo[gameData.level].stars
    if stars_ > 0 then 
        self.star1:setVisible(true) 
        d_print("light star1")
    end
    if stars_ > 1 then 
        self.star2:setVisible(true) 
        d_print("light star2")
    end
    if stars_ > 2 then 
        self.star3:setVisible(true) 
        d_print("light star3")
    end


    --删除已有的bmfont lines
    if self.descLines then
        for k,v in ipairs(self.descLines)do
            v:removeFromParent(true)
        end
    end

    uiBMFont:setAddInfo(self.ui_levelinfo, s_uiinfo_desc.zorder)
    uiBMFont:setColor(cc.c3b(205,233,255))
    self.descLines = uiBMFont:createMultiLines( "        "..s_levelDesc[gameData.level], pp.fnt_common, 0.65, 300, s_uiinfo_desc.position.x, s_uiinfo_desc.position.y, 21)
end

function LevelScene:refreshCoin(showcoin)
    -- body
    local str = string.format("%d", showcoin)
    self.ui_fnt_coin:setString(str)
end

function LevelScene:refreshLiveCnt()
    -- body
    if userData.lives == userData.fulllives then
        self.ui_fnt_lefttime:setString("")
    end
    self.ui_fnt_livescnt:setString(string.format("%d",userData.lives))
end

function LevelScene:checkLoginObjects()
    local popAward = false
    if gameData.loginChecked == false then
        --award
        local awardStatus = gameUtil.checkLoginAwardStatus()
        if awardStatus ~= pp.loginAwardStatus.got then
            local loginAwardPanel = LoginAwardPanel.create(self, awardStatus)
            loginAwardPanel:popIn(0.3)
            popAward = true
        end

        ----------------------------------    
        gameData.loginChecked = true 
    end
    return popAward
end

function LevelScene:unlockLock( )
    -- body
    local showlevelcnt = #userData.passedlevelinfo
    local level = showlevelcnt / levelCfg.lockInterval
    local idx = math.floor(level)
    local lock = self.locks[idx]
    lock:setEnabled(false)
    -- self.yellowLock:removeFromParent(true)

    lock:loadTextureNormal(s_img_lock_unlocked, ccui.TextureResType.localType)

    self:activeLevel(showlevelcnt)

    local bt = self.ui_btCtn:getChildByTag(showlevelcnt)
    local x,y = bt:getPosition()
    self.focusEft:setPosition(cc.p(x,y - 10))
    
    gameUtil.unlockTheLock()

    --lkj hardcode:
    if uiIndicator.inst then
        uiIndicator.inst:setPosition(cc.p(x,y +70))
    end
end

function LevelScene:popLevelPanel()
    -- body    
    -- uiEffect.maskIn(self.base_mask)

    self:levelPanelInit()
    self.ui_levelinfo:setVisible(true)
    uiEffect.bounceIn(self.ui_levelinfo)


    
    --lkj hard code: for this special state    最开始写的代码，没时间改了：ui_levelinfo是个view，没有进行panel封装
    -- self.base_popWinStack[#self.base_popWinStack+1] = self.ui_levelinfo
    -- if #self.base_popWinStack == 1 then
    --     uiEffect.maskIn(self.base_mask)
    -- end
    -- local zorder = self.ui_levelinfo:getLocalZOrder()
    -- self.base_mask:setLocalZOrder(zorder - 1)

    self:base_onOpenWin(self.ui_levelinfo)
    -----------------------------------------------
end


function LevelScene:uni_onChildClose(child)
    -- body
    -- self.uni
end